import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import axios from 'axios';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const req = ctx.getRequest();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const logData = {
      originalUrl: req.originalUrl,
      Method: req.method,
      Ip: req.ip,
      statusCode: status,
      Parmas: JSON.stringify(req.params),
      Query: JSON.stringify(req.query),
      Body: JSON.stringify(req.body),
    };

    if (!req.ip.includes('127.0.0.1')) {
      axios
        .post(
          'https://open.feishu.cn/open-apis/bot/v2/hook/b90f0bbb-a597-4148-aba5-16b3c53ccf28',
          {
            msg_type: 'post',
            content: {
              post: {
                zh_cn: {
                  title: '【tanjirou接口异常】',
                  content: [
                    [
                      {
                        tag: 'text',
                        text: '用户:',
                      },
                      {
                        tag: 'text',
                        text: req.user ? req.user.name : '无',
                      },
                      {
                        tag: 'text',
                        text: '\n信息:\n',
                      },
                      {
                        tag: 'text',
                        text: JSON.stringify(
                          logData,
                          function replacer(key, value) {
                            if (typeof value === undefined) {
                              return undefined;
                            }
                            return value;
                          },
                          4,
                        ),
                      },
                    ],
                    [
                      {
                        tag: 'text',
                        text: '错误信息:',
                      },
                      {
                        tag: 'text',
                        text: exception.stack,
                      },
                    ],
                  ],
                },
              },
            },
          },
        )
        .catch((err) => {
          console.error(err);
        });
    }

    response.status(status).json({
      statusCode: status,
      msg: `Service Error: ${exception}`,
    });
  }
}
